package com.example.huangliting.experimentalarrangementsystem.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.huangliting.experimentalarrangementsystem.R;
import com.example.huangliting.experimentalarrangementsystem.ScheduleView;
import com.example.huangliting.experimentalarrangementsystem.activity.AddLessonActivity;
import com.example.huangliting.experimentalarrangementsystem.activity.ClassDetailActivity;
import com.example.huangliting.experimentalarrangementsystem.activity.LoginActivity;
import com.example.huangliting.experimentalarrangementsystem.activity.MainActivity;
import com.example.huangliting.experimentalarrangementsystem.activity.MyScheduleViewAct;
import com.example.huangliting.experimentalarrangementsystem.activity.SetWeekActivity;
import com.example.huangliting.experimentalarrangementsystem.activity.ViewConditionsActivity;
import com.example.huangliting.experimentalarrangementsystem.bean.BoxMsg;
import com.example.huangliting.experimentalarrangementsystem.bean.ClassInfo;
import com.example.huangliting.experimentalarrangementsystem.bean.Laboratory;
import com.example.huangliting.experimentalarrangementsystem.util.DateUitls;
import com.example.huangliting.experimentalarrangementsystem.util.HttpUtils;
import com.example.huangliting.experimentalarrangementsystem.util.MD5Utils;
import com.example.huangliting.experimentalarrangementsystem.util.Utils;
import com.example.huangliting.experimentalarrangementsystem.view.KBCalendar;
import com.example.huangliting.experimentalarrangementsystem.view.TwoWayView;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by HuangLiting on 2018/3/19.
 */

public class ScheduleFragment extends Fragment implements KBCalendar.IKBAgendaEvent {

    public ScheduleFragment() {
    }

    final String getDataUrl = HttpUtils.headerUrl + "timetable";
    final String updateUrl = HttpUtils.headerUrl + "timetable/updateData";
    final String updateDateAndTitleUrl = HttpUtils.headerUrl + "timetable/updateTitleAndDate";
    private int nextclassNum = 0;
    private ScheduleView scheduleView;
    private TwoWayView twoWayView;
    private ArrayList<ClassInfo> classList;
    private List<String> nameStrX;
    private List<Laboratory> laboratories;
    private TextView mDataSelect;
    private TextView mDataScroll;
    private TextView title_tv;
    private TextView title_tv_small;
    private boolean isKBCalendarVisible = true;
    private LinearLayout titleLinearLayout;
    private Button addBtn;
    private Button refreshBtn;
    private TopRightMenu mTopRightMenu;
    private String selectDate = null;
    private KBCalendar mKBCalendar;
    private boolean isAlltable = true;
    private SharedPreferences sp;
    private String titleStr;
    private int thisWeekNum;
    private String semesterStr;
    private int selectWeekDay = 0;
    private ArrayList<Date> mListDays;
    private Date thisWeekStartDate;
    private Date thisWeekEndDate;
    private Date timetableDate;

    public static final int SHOW_RESPONSE = 0;

    JSONArray timetable = null;
    JSONArray nameX = null;
    JSONObject titleJson = null;

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        final View view = inflater.inflate(R.layout.fragment_schedule, container, false);

        /*
         *初始化课程信息
         */
        scheduleView = (ScheduleView) view.findViewById(R.id.scheduleView);
        twoWayView = (TwoWayView) view.findViewById(R.id.list);
        title_tv = view.findViewById(R.id.toolbar_title_tv);
        title_tv_small = view.findViewById(R.id.toolbar_title_tv_small);
        titleLinearLayout = (LinearLayout) view.findViewById(R.id.title_LinearLayout);
        sp = getActivity().getSharedPreferences("userInfo", Context.MODE_PRIVATE);

        //getClassData();获取课程数据
        sendRequestWithHttpURLConnection();
        //scheduleView.setClassList(classList);// 将课程信息导入到课表中
        Log.i("classList:", "" + classList);
        Log.i("scheduleView:", "" + scheduleView);

        //有课时点击课程
        scheduleView.setOnItemClassClickListener(new ScheduleView.OnItemClassClickListener() {
            @Override
            public void onClick(ClassInfo classInfo) {
                /*Toast.makeText(view.getContext(),
                        "您点击的课程是：" + classInfo.getClassname(),
                        Toast.LENGTH_SHORT).show();*/
                Intent i = new Intent(getActivity(), ClassDetailActivity.class);
                Bundle b = new Bundle();
                b.putInt("cid", classInfo.getClassid());
                i.putExtras(b);
                startActivity(i);
            }
        });

        //无课时点击添加
        scheduleView.setOnNoItemClassClickListener(new ScheduleView.OnItemNoClassClickListener() {
            @Override
            public void onClick(BoxMsg boxMsg) {

                //未登录不能排课
                if(!sp.getBoolean("isLogin",false)){
                    Toast.makeText(view.getContext(),"请先登录，登录后才能排课",Toast.LENGTH_LONG).show();
                    return;
                }

                //提示全部'课程模式下预排课
                if(!isAlltable){
                    AlertDialog.Builder builder  = new AlertDialog.Builder(getView().getContext());
                    builder.setTitle("提示" ) ;
                    builder.setMessage("请在'全部'课程模式下点击预排课") ;
                    builder.setPositiveButton("知道了" ,  null );
                    builder.show();
                    return;
                }

                //提示选择日期不在查看周
                if( timetableDate.before(thisWeekStartDate) || thisWeekEndDate.before(timetableDate) ){
                    AlertDialog.Builder builder  = new AlertDialog.Builder(getView().getContext());
                    builder.setTitle("提示" ) ;
                    builder.setMessage("当前课表显示的日期为："+DateFormat.format("yyyy-MM-dd", timetableDate).toString()+"，不在第"+thisWeekNum+"周的"+DateFormat.format("yyyy-MM-dd", thisWeekStartDate).toString()+"和"
                            +DateFormat.format("yyyy-MM-dd", thisWeekEndDate).toString()+"之间。\n提示：您先选择第"+thisWeekNum+"周中的日期！点击标题栏展开选择" ) ;
                    builder.setPositiveButton("知道了" ,  null );
                    builder.show();
                    return;
                }

                //提示选择日期
                if( timetableDate.before(new Date())){
                    Toast.makeText(view.getContext(),"已过预排课时间",Toast.LENGTH_LONG).show();
                    return;
                }

                Intent i = new Intent(getActivity(), AddLessonActivity.class);
                Bundle b = new Bundle();
                //b.putInt("nextclassNum", boxMsg.getNextclassNum());
                b.putInt("xnum", laboratories.get(boxMsg.getxNum()-1).getLid());
                b.putInt("ynum", boxMsg.getyNum());
                b.putInt("weekday", selectWeekDay);
                b.putString("classAddr", nameStrX.get(boxMsg.getxNum() - 1));
                b.putString("classDate", String.valueOf(selectDate));
                try {
                    b.putString("weekid", titleJson.getString("weekid"));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                i.putExtras(b);
                startActivityForResult(i, 1);

            }
        });

        //周时间段
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());

        mDataSelect = (TextView) view.findViewById(R.id.data_select);
        selectDate = DateFormat.format("yyyy-MM-dd", new Date()).toString();
        String formatDate = "yyyy-MM-dd";
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatDate);
        try {
            timetableDate = dateFormat.parse(selectDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        mDataSelect.setText(DateFormat.format("yyyy年MM月dd日", new Date()).toString() + " " + DateUitls.formateDay(cal.get(Calendar.DAY_OF_WEEK)));
        selectWeekDay = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (selectWeekDay == 0)
            selectWeekDay = selectWeekDay + 7;

        mDataScroll = (TextView) view.findViewById(R.id.data_scroll);

        /*选择时间初始化组件*/
        mListDays = new ArrayList<Date>();
        Date dateStartCalendar = null;
        Date dateEndCalendar = null;

        try {
            dateStartCalendar = dateFormat.parse("2014-05-07");
            dateEndCalendar = dateFormat.parse("2018-06-18");
        } catch (ParseException e1) {
            e1.printStackTrace();
        }

        GregorianCalendar calendar = new GregorianCalendar();

        calendar.setTime(dateStartCalendar);
        Date dateStartBefore = calendar.getTime();
        calendar.setTime(dateEndCalendar);
        int day = calendar.get(Calendar.DATE);
        calendar.set(Calendar.DATE, day + 1);
        Date dateEndAfter = calendar.getTime();

        for (Date date = dateStartBefore; !date.equals(dateEndAfter); ) {
            calendar.setTime(date);
            mListDays.add(date);
            calendar.add(Calendar.DATE, 1);
            date = calendar.getTime();
        }

        mKBCalendar = new KBCalendar(view.getContext(), this);
        mKBCalendar.setListDays(mListDays);
        mKBCalendar.loadKBCalendar(view);

        titleLinearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isKBCalendarVisible) {
                    twoWayView.setVisibility(View.VISIBLE);
                    isKBCalendarVisible = false;
                } else {
                    twoWayView.setVisibility(View.GONE);
                    isKBCalendarVisible = true;
                }
            }
        });

        /*更多 ic_add*/
        addBtn = (Button) view.findViewById(R.id.toolbar_right_btn);
        addBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                mTopRightMenu = new TopRightMenu((Activity) view.getContext());
                final List<MenuItem> menuItems = new ArrayList<>();
                menuItems.add(new MenuItem(R.drawable.ic_add_lesson, "新增课程"));
                menuItems.add(new MenuItem(R.drawable.ic_mylesson, "查看条件"));
                menuItems.add(new MenuItem(R.drawable.ic_share, "全部课表"));
                //登录状态
                if (sp.getBoolean("isLogin", false) && isAlltable)
                    menuItems.get(2).setText("我的课表");
                mTopRightMenu
                        .setHeight(500)     //默认高度480
                        .setWidth(450)      //默认宽度wrap_content
                        .showIcon(true)     //显示菜单图标，默认为true
                        .dimBackground(true)           //背景变暗，默认为true
                        .needAnimationStyle(true)   //显示动画，默认为true
                        .setAnimationStyle(R.style.TRM_ANIM_STYLE)  //默认为R.style.TRM_ANIM_STYLE
                        .addMenuList(menuItems)
                        .setOnMenuItemClickListener(new TopRightMenu.OnMenuItemClickListener() {
                            @Override
                            public void onMenuItemClick(int position) {
                                //Toast.makeText(view.getContext(), "点击菜单:" + position, Toast.LENGTH_SHORT).show();
                                if (position == 0) {
                                    AlertDialog.Builder builder  = new AlertDialog.Builder(getView().getContext());
                                    builder.setTitle("提示" ) ;
                                    builder.setMessage("请在'全部'课程模式下点击课表空白处进行预排课，请提前至少一个工作日排课！") ;
                                    builder.setPositiveButton("知道了" ,  null );
                                    builder.show();
                                }

                                if (position == 1) {
                                    Intent i = new Intent(getActivity(), SetWeekActivity.class);
                                    Bundle b = new Bundle();
                                    b.putInt("thisWeekNum", thisWeekNum);
                                    b.putString("semester", semesterStr);
                                    i.putExtras(b);
                                    startActivityForResult(i, 2);
                                }

                                if (position == 2) {

                                    if (sp.getBoolean("isLogin", false)) {
                                        if (isAlltable) {
                                            menuItems.get(position).setText("我的课表");
                                            title_tv.setText(titleStr + "(我的)");
                                            isAlltable = false;
                                            touchUpdate();
                                        } else {
                                            menuItems.get(position).setText("全部课表");
                                            title_tv.setText(titleStr + "(全部)");
                                            isAlltable = true;
                                            touchUpdate();
                                        }
                                    }


                                }

                            }
                        })
                        .showAsDropDown(addBtn, -350, 0);
                //.showAsDropDown(moreBtn);
            }
        });

        //刷新
        refreshBtn = view.findViewById(R.id.toolbar_left_btn);
        refreshBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            touchUpdate();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();
            }
        });
        return view;
    }

    // 单选提示框
    private AlertDialog alertDialog2;

    public void showSingleAlertDialog(final View view) {
        final String[] items = {"Struts2", "Spring", "Hibernate", "Mybatis", "Spring MVC"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(view.getContext());
        alertBuilder.setTitle("选择课表查看条件");
        alertBuilder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int index) {
                Toast.makeText(view.getContext(), items[index], Toast.LENGTH_SHORT).show();
            }
        });
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                //TODO 业务逻辑代码

                // 关闭提示框
                alertDialog2.dismiss();
            }
        });
        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO 业务逻辑代码

                // 关闭提示框
                alertDialog2.dismiss();
            }
        });
        alertDialog2 = alertBuilder.create();
        alertDialog2.show();
    }

    private void getClassData() {
        classList = new ArrayList<ClassInfo>();
        ClassInfo classInfo = new ClassInfo();
        classInfo.setClassname("数据库原理与");
        classInfo.setFromClassNum(3);
        classInfo.setClassNumLen(2);
        classInfo.setClassRoom("C1-403");
        classInfo.setWeekday(1);
        classList.add(classInfo);

        ClassInfo classInfo1 = new ClassInfo();
        classInfo1.setClassname("人机交互");
        classInfo1.setFromClassNum(6);
        classInfo1.setClassNumLen(3);
        classInfo1.setClassRoom("信息机房");
        classInfo1.setWeekday(1);
        classList.add(classInfo1);

        ClassInfo classInfo2 = new ClassInfo();
        classInfo2.setClassname("物联网技术及应用");
        classInfo2.setFromClassNum(3);
        classInfo2.setClassNumLen(3);
        classInfo2.setClassRoom("C1-101");
        classInfo2.setWeekday(3);
        classList.add(classInfo2);

        ClassInfo classInfo3 = new ClassInfo();
        classInfo3.setClassname("应用集成原理与工具");
        classInfo3.setFromClassNum(6);
        classInfo3.setClassNumLen(2);
        classInfo3.setClassRoom("C1-205");
        classInfo3.setWeekday(3);
        classList.add(classInfo3);

        ClassInfo classInfo4 = new ClassInfo();
        classInfo4.setClassname("linux系统");
        classInfo4.setFromClassNum(3);
        classInfo4.setClassNumLen(2);
        classInfo4.setClassRoom("C1-205");
        classInfo4.setWeekday(5);
        classList.add(classInfo4);
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE:
                    String response = (String) msg.obj;          // 在这里进行UI操作，将结果显示到界面上
                    //responseText.setText(response);
            }
        }
    };

    /*获取数据*/
    private void sendRequestWithHttpURLConnection() {
        //开启线程来发起网络请求
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(getDataUrl);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    //connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();                    // 下面对获取到的输入流进行读取
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    Message message = new Message();
                    message.what = SHOW_RESPONSE;                    // 将服务器返回的结果存放到Message中
                    message.obj = response.toString();
                    handler.sendMessage(message);

                    final String resp = response.toString();
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            parseJSON(resp);
                        }
                    });


                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();

    }

    //解析和初始化数据
    private void parseJSON(String jsonData) {
        try {
            JSONObject jsonObj1 = new JSONObject(jsonData);
            // Getting JSON Array node
            nameX = jsonObj1.getJSONArray("fromX");
            titleJson = jsonObj1.getJSONObject("thisweek");
            nameStrX = new ArrayList<String>();
            laboratories = new ArrayList<>();
            for (int i = 0; i < nameX.length(); i++) {
                JSONObject jsonObjectTemp = nameX.getJSONObject(i);
                String lnameStr = jsonObjectTemp.getString("lname");
                Laboratory laboratory = new Laboratory();
                laboratory.setLid(jsonObjectTemp.getInt("lid"));
                laboratory.setLname(lnameStr);
                nameStrX.add(lnameStr);
                laboratories.add(laboratory);
            }
            scheduleView.setNameX(nameStrX);
            if (titleJson != null) {
                title_tv_small.setText(titleJson.getString("semester"));
                title_tv.setText("第" + titleJson.getString("weekNum") + "周(全部)");
                titleStr = "第" + titleJson.getString("weekNum") + "周";
                thisWeekNum = titleJson.getInt("weekNum");
                semesterStr = titleJson.getString("semester");
                mListDays = new ArrayList<Date>();
                String formatDate = "yyyy-MM-dd";
                SimpleDateFormat dateFormat = new SimpleDateFormat(formatDate);
                Date dateStartCalendar = null;
                Date dateEndCalendar = null;


                try {

                    dateStartCalendar = dateFormat.parse(titleJson.getString("weekStartDate"));
                    dateEndCalendar = dateFormat.parse(titleJson.getString("weekEndDate"));
                    //记录该周的起末日期
                    thisWeekStartDate = dateStartCalendar;
                    thisWeekEndDate = dateEndCalendar;
                    GregorianCalendar calendar = new GregorianCalendar();

                    calendar.setTime(dateStartCalendar);
                    Date dateStartBefore = calendar.getTime();
                    calendar.setTime(dateEndCalendar);
                    int day = calendar.get(Calendar.DATE);
                    calendar.set(Calendar.DATE, day + 1);
                    Date dateEndAfter = calendar.getTime();

                    for (Date date = dateStartBefore; !date.equals(dateEndAfter); ) {
                        calendar.setTime(date);
                        mListDays.add(date);
                        calendar.add(Calendar.DATE, 1);
                        date = calendar.getTime();
                    }

                    mKBCalendar = new KBCalendar(getView().getContext(), this);
                    mKBCalendar.setListDays(mListDays);
                    mKBCalendar.loadKBCalendar(getView());
                } catch (ParseException e1) {
                    e1.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        try {

            JSONObject jsonObj = new JSONObject(jsonData);
            // Getting JSON Array node
            timetable = jsonObj.getJSONArray("timetable");

            classList = new ArrayList<ClassInfo>();
            for (int i = 0; i < timetable.length(); i++) {
                ClassInfo classInfo = new ClassInfo();
                JSONObject jsonObject = timetable.getJSONObject(i);
                classInfo.setClassid(jsonObject.getInt("cid"));
                classInfo.setClassname(jsonObject.getString("lessonName"));
                classInfo.setFromClassNum(jsonObject.getInt("classNum"));
                classInfo.setClassNumLen(jsonObject.getInt("classLength"));
                classInfo.setClassRoom(jsonObject.getString("lname"));
                classInfo.setxNum(jsonObject.getInt("xNum"));
                classInfo.setTeacherName(jsonObject.getString("tname"));
                //classInfo.setWeekday(1);
                classList.add(classInfo);
            }
            scheduleView.setClassList(classList);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDateSelect(Date date) {
        timetableDate = date;
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        selectDate = DateFormat.format("yyyy-MM-dd", date).toString();
        Log.i("KBCalendar", "Date : " + DateFormat.format("yyyy-MM-dd", date).toString());
        mDataSelect.setText(DateFormat.format("yyyy年MM月dd日", date).toString() + " " + DateUitls.formateDay(cal.get(Calendar.DAY_OF_WEEK)));
        //记录选择了周几
        if(cal.get(Calendar.DAY_OF_WEEK) == 1){
            selectWeekDay = 7;
        }else
            selectWeekDay = cal.get(Calendar.DAY_OF_WEEK) -1;
        touchUpdate();
    }

    //更新我的或全部课表数据
    private void touchUpdate() {
        //识别课表类型
        String tableSign;
        if (isAlltable)
            tableSign = "all";
        else
            tableSign = "person";

        Map<String, String> params = new HashMap<String, String>();
        params.put("userId", sp.getString("userId", ""));
        params.put("searchDate", selectDate);
        params.put("tableSign", tableSign);
        updateDataByPost(params, "utf-8");
    }

    @Override
    public void onListScroll(Date date) {
        Log.i("KBCalendar", "onListScrollDate : " + DateFormat.format("yyyy-MM-dd", date).toString());
        mDataScroll.setText(DateFormat.format("yyyy年MM月dd日", date).toString());
    }

    /**
     * 此方法用来跳转的activity要传回的数据，以及接受到传回数据的要做的业务
     * 这里因为只有一个activity返回数据，所以这里就只有一个resultCode，就直接接收返回值处理
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (1 == requestCode) {
            touchUpdate();
        }
        if (2 == requestCode) {
            Bundle bundle = data.getExtras();
            Map<String, String> params = new HashMap<String, String>();
            params.put("weekid", bundle.getString("weekid"));
            updateDateAndTitleByPost(params, "utf-8");
        }
    }

    //更新时间和标题
    Handler updateDateHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            parseUpdateDateJSON((String) msg.obj);
        }
    };

    //更新时间和标题解析JSON数据
    private void parseUpdateDateJSON(String obj) {
        try {
            JSONObject jsonObj = new JSONObject(obj);
            titleJson = jsonObj.getJSONObject("weekMsg");
            if (titleJson != null) {
                title_tv_small.setText(titleJson.getString("semester"));
                title_tv.setText("第" + titleJson.getString("weekNum") + "周(全部)");
                titleStr = "第" + titleJson.getString("weekNum") + "周";
                thisWeekNum = titleJson.getInt("weekNum");
                semesterStr = titleJson.getString("semester");
                ArrayList<Date> mListDays = new ArrayList<Date>();
                String formatDate = "yyyy-MM-dd";
                SimpleDateFormat dateFormat = new SimpleDateFormat(formatDate);
                Date dateStartCalendar = null;
                Date dateEndCalendar = null;

                try {
                    dateStartCalendar = dateFormat.parse(titleJson.getString("weekStartDate"));
                    dateEndCalendar = dateFormat.parse(titleJson.getString("weekEndDate"));
                    //更新该周的起末日期
                    thisWeekStartDate = dateStartCalendar;
                    thisWeekEndDate = dateEndCalendar;
                    GregorianCalendar calendar = new GregorianCalendar();

                    calendar.setTime(dateStartCalendar);
                    Date dateStartBefore = calendar.getTime();
                    calendar.setTime(dateEndCalendar);
                    int day = calendar.get(Calendar.DATE);
                    calendar.set(Calendar.DATE, day + 1);
                    Date dateEndAfter = calendar.getTime();

                    for (Date date = dateStartBefore; !date.equals(dateEndAfter); ) {
                        calendar.setTime(date);
                        mListDays.add(date);
                        calendar.add(Calendar.DATE, 1);
                        date = calendar.getTime();
                    }

                    mKBCalendar = new KBCalendar(getView().getContext(), this);
                    mKBCalendar.setListDays(mListDays);
                    mKBCalendar.loadKBCalendar(getView());
                } catch (ParseException e1) {
                    e1.printStackTrace();
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //更新时间和标题的请求
    private void updateDateAndTitleByPost(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(updateDateAndTitleUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = updateDateHandler.obtainMessage();
                        msg.obj = text;
                        updateDateHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }

    //根据选项更新表格数据
    Handler updateHandler = new Handler() {

        @SuppressLint("WrongConstant")
        public void handleMessage(android.os.Message msg) {
            try {
                JSONObject jsonObj = new JSONObject((String) msg.obj);
                timetable = jsonObj.getJSONArray("timetable");

                classList = new ArrayList<ClassInfo>();
                for (int i = 0; i < timetable.length(); i++) {
                    ClassInfo classInfo = new ClassInfo();
                    JSONObject jsonObject = timetable.getJSONObject(i);
                    classInfo.setClassid(jsonObject.getInt("cid"));
                    classInfo.setClassname(jsonObject.getString("lessonName"));
                    classInfo.setFromClassNum(jsonObject.getInt("classNum"));
                    classInfo.setClassNumLen(jsonObject.getInt("classLength"));
                    classInfo.setClassRoom(jsonObject.getString("lname"));
                    classInfo.setxNum(jsonObject.getInt("xNum"));
                    classInfo.setTeacherName(jsonObject.getString("tname"));
                    classList.add(classInfo);
                }
                scheduleView.setClassList(classList);

            } catch (Exception e) {
                e.printStackTrace();
            }
            //Toast.makeText(AddLessonActivity.this, (String)msg.obj, Toast.LENGTH_LONG).show();
        }
    };

    //根据选项更新表格数据(我的，全部)
    private void updateDataByPost(final Map<String, String> params, final String encode) {
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    URL url = new URL(updateUrl);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("POST");
                    conn.setConnectTimeout(5000);
                    conn.setReadTimeout(5000);

                    //拼接出要提交的数据的字符串
                    byte[] data = HttpUtils.getRequestData(params, encode).toString().getBytes();

                    //添加post请求的两行属性
                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    conn.setRequestProperty("Content-Length", String.valueOf(data.length));

                    //设置打开输出流
                    conn.setDoOutput(true);
                    //拿到输出流
                    OutputStream os = conn.getOutputStream();
                    //使用输出流往服务器提交数据
                    os.write(data);
                    if (conn.getResponseCode() == 200) {
                        InputStream is = conn.getInputStream();
                        String text = Utils.getTextFromStream(is);
                        Message msg = updateHandler.obtainMessage();
                        msg.obj = text;
                        updateHandler.sendMessage(msg);
                    }
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        t.start();
    }
}
